package Viewer;

import java.awt.Event;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;

import DataModel.Tupel;
import Export.BlastThread;
import Export.ExportBed12;
import Export.ExportGenBank;
import Export.ExportGff3;
import Export.ExportGtf;
import Export.ExportImage;
import Export.ExportSequence;
import Export.ExportWebLogo;

/**
 * The menu bar of the {@link Viewer}
 * 
 * @author Stefan Lorenz<br>
 * <br>
 *         29.11.2012
 */
@SuppressWarnings("serial")
public class Menue extends JMenuBar {

	/**
	 * Show if the fullscreen mode was enabled or disabled
	 */
	protected boolean isFullScreen = false;

	/**
	 * The constructor of the menu
	 * 
	 * @param viewer
	 *            viewer of the genscapes session
	 */
	public Menue(final Viewer viewer) {
		this.setLayout(new GridBagLayout());
		GridBagConstraints gc = new GridBagConstraints();

		JMenu trackMenu = new JMenu("Tracks");
		ImageIcon trackIcon = new ImageIcon(Menue.class.getResource("../resources/track32.png"));
		final ImageIcon selectecIcon = new ImageIcon(Menue.class.getResource("../resources/check.png"));
		trackMenu.setIcon(trackIcon);

		gc.fill = GridBagConstraints.NONE;
		gc.anchor = GridBagConstraints.LINE_START;
		gc.gridheight = 1;
		gc.gridwidth = 1;
		gc.insets = new Insets(0, 0, 0, 0);
		gc.gridy = 0;

		gc.gridx = 0;
		this.add(trackMenu, gc);
		JMenuItem openTrack = new JMenuItem("Open Track Table...");
		trackMenu.add(openTrack);
		openTrack.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				try {
					viewer.getTrackTable().getWindow().dispose();
				}
				catch (Exception e1) {
				}
				viewer.setTrackTable(new TrackTable(viewer));
			}
		});

		JMenuItem resetTrackPositions = new JMenuItem("Reset Track Positions");
		resetTrackPositions.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.Event.CTRL_MASK));
		trackMenu.add(resetTrackPositions);
		resetTrackPositions.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				viewer.resetTrackPositions();
			}
		});

		JMenu download = new JMenu("Export");
		ImageIcon exportSeqIcon = new ImageIcon(Menue.class.getResource("../resources/export32.png"));
		download.setIcon(exportSeqIcon);
		gc.gridx = 1;
		this.add(download, gc);

		JMenu selected = new JMenu("Export Selected Features");
		download.add(selected);

		JMenu asFasta = new JMenu("As FastA");
		selected.add(asFasta);

		JMenuItem dnaSeq = new JMenuItem("DNA");
		dnaSeq.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (viewer.getFileChooser().showSaveDialog(viewer) == JFileChooser.APPROVE_OPTION)
					new ExportSequence(viewer, "DNA", viewer.getFileChooser().getSelectedFile().getAbsolutePath());
			}
		});
		asFasta.add(dnaSeq);

		JMenuItem mRNASeq = new JMenuItem("RNA");
		mRNASeq.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (viewer.getFileChooser().showSaveDialog(viewer) == JFileChooser.APPROVE_OPTION)
					new ExportSequence(viewer, "RNA", viewer.getFileChooser().getSelectedFile().getAbsolutePath());
			}
		});
		asFasta.add(mRNASeq);

		JMenuItem aminoAcid = new JMenuItem("AA");
		aminoAcid.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (viewer.getFileChooser().showSaveDialog(viewer) == JFileChooser.APPROVE_OPTION)
					new ExportSequence(viewer, "AA", viewer.getFileChooser().getSelectedFile().getAbsolutePath());
			}
		});
		asFasta.add(aminoAcid);

		JMenuItem asGenbank = new JMenuItem("As GenBank...");
		asGenbank.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				new ExportGenBank(viewer, viewer.getSelectedFeatureList());
			}
		});
		asGenbank.setActionCommand("asGenbank");
		selected.add(asGenbank);

		JMenuItem asGff3 = new JMenuItem("As Gff3...");
		asGff3.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				new ExportGff3(viewer.getSelectedFeatureList(), viewer.getFileChooser());
			}
		});
		asGff3.setActionCommand("asGenbank");
		selected.add(asGff3);

		JMenuItem asGTF = new JMenuItem("As GTF...");
		asGTF.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				new ExportGtf(viewer.getSelectedFeatureList(), viewer.getFileChooser());
			}
		});
		asGTF.setActionCommand("asGTF");
		selected.add(asGTF);
		
		JMenuItem asBed = new JMenuItem("As Bed12...");
		asBed.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				new ExportBed12(viewer.getSelectedFeatureList(), viewer.getFileChooser());
			}
		});
		asBed.setActionCommand("asGTF");
		selected.add(asBed);
		
		

		JMenuItem exportAnnotation = new JMenuItem("Export ABC Track...");
		exportAnnotation.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				new ExportGenBank(viewer, viewer.getLoadedTracks()[0]);
			}
		});
		download.add(exportAnnotation);

		JMenuItem export = new JMenuItem("Export PDF...");
		export.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				new ExportImage(viewer.getDrawPanel(), viewer.getFileChooser());
			}
		});
		download.add(export);

		JMenu exportSeqlogo = new JMenu("Export Sequence Logo");
		download.add(exportSeqlogo);
		JMenuItem seqLogoDNA = new JMenuItem("DNA");
		seqLogoDNA.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				new ExportWebLogo(viewer, "DNA");
			}
		});
		exportSeqlogo.add(seqLogoDNA);

		JMenuItem seqLogoMRNA = new JMenuItem("RNA");
		seqLogoMRNA.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				new ExportWebLogo(viewer, "RNA");
			}
		});
		exportSeqlogo.add(seqLogoMRNA);

		JMenuItem seqLogoAA = new JMenuItem("AA");
		seqLogoAA.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				new ExportWebLogo(viewer, "AA");
			}
		});
		exportSeqlogo.add(seqLogoAA);

		final JMenu analyseMenu = new JMenu("Analyse");
		final ImageIcon anaIcon = new ImageIcon(Menue.class.getResource("../resources/analyse32.png"));
		analyseMenu.setIcon(anaIcon);
		gc.gridx = 3;
		this.add(analyseMenu, gc);

		final JMenuItem searchShift = new JMenuItem("Show Search & Shift");
		searchShift.setAccelerator(KeyStroke.getKeyStroke('s'));

		searchShift.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

				if (viewer.isSearchShiftVisible()) {
					viewer.setSearchShiftVisible(false);
					searchShift.setIcon(null);
				}
				else {
					viewer.setSearchShiftVisible(true);
					searchShift.setIcon(selectecIcon);
				}
			}
		});
		analyseMenu.add(searchShift);

		final JMenuItem selectionMode = new JMenuItem("Selection Frame Mode");
		selectionMode.setAccelerator(KeyStroke.getKeyStroke('f'));

		selectionMode.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

				if (viewer.getDrawPanel().isShowSelectionFrame()) {
					viewer.getDrawPanel().setShowSelectionFrame(false);
					selectionMode.setIcon(null);
				}
				else {
					viewer.getDrawPanel().setShowSelectionFrame(true);
					selectionMode.setIcon(selectecIcon);
				}
			}
		});
		analyseMenu.add(selectionMode);

		final JMenuItem selectedSequence = new JMenuItem("Frame Annotation Mode");
		selectedSequence.setAccelerator(KeyStroke.getKeyStroke('c'));

		selectedSequence.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

				if (viewer.getDrawPanel().isSelectionSequences()) {
					viewer.getDrawPanel().setSelectSequences(false);
					selectedSequence.setIcon(null);
				}
				else {
					viewer.getDrawPanel().setSelectSequences(true);
					selectedSequence.setIcon(selectecIcon);
				}
			}
		});
		analyseMenu.add(selectedSequence);

		JMenuItem searchOrthologues = new JMenuItem("Find Orthologue Of Selected");
		searchOrthologues.setAccelerator(KeyStroke.getKeyStroke('g'));

		searchOrthologues.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				viewer.findOrthologueInTrack();
			}
		});
		analyseMenu.add(searchOrthologues);

		JMenuItem blast = new JMenuItem("Blast Selected");
		blast.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if(viewer.getFileChooser().showSaveDialog(viewer) == JFileChooser.APPROVE_OPTION)
					new BlastThread(viewer.getFileChooser().getSelectedFile(), viewer.getSelectedSequences());
			}
		});
		analyseMenu.add(blast);

		JMenu annoMenu = new JMenu("Annotator");
		final ImageIcon anno = new ImageIcon(Menue.class.getResource("../resources/annotator32.png"));
		annoMenu.setIcon(anno);
		gc.gridx = 4;
		this.add(annoMenu, gc);

		final JMenu transTable = new JMenu("Translation Table");
		ActionListener transTableListener = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				viewer.getAminoAcidTable().setTranslTable(Integer.valueOf(e.getActionCommand()));
				System.out.println("Switched translation table to " + Integer.valueOf(e.getActionCommand()));

				for (int i = 0; i < viewer.getSettings().getSixFrameSettings().length; i++) {
					viewer.getSettings().getSixFrameSettings()[i].setStartStop(viewer.getAminoAcidTable().getStartCodons(), viewer.getAminoAcidTable().getStopCodons());
				}
				for (int i = 0; i < transTable.getMenuComponents().length; i++) {
					((JMenuItem) transTable.getMenuComponents()[i]).setIcon(null);
				}
				((JMenuItem) e.getSource()).setIcon(selectecIcon);
				viewer.getDrawPanel().repaint();
			}
		};
		JMenuItem transTable1 = new JMenuItem("transl_table = 1", selectecIcon);
		transTable.add(transTable1);
		JMenuItem transTable2 = new JMenuItem("transl_table = 2");
		transTable.add(transTable2);
		JMenuItem transTable3 = new JMenuItem("transl_table = 3");
		transTable.add(transTable3);
		JMenuItem transTable4 = new JMenuItem("transl_table = 4");
		transTable.add(transTable4);
		JMenuItem transTable5 = new JMenuItem("transl_table = 5");
		transTable.add(transTable5);
		JMenuItem transTable6 = new JMenuItem("transl_table = 6");
		transTable.add(transTable6);
		JMenuItem transTable9 = new JMenuItem("transl_table = 9");
		transTable.add(transTable9);
		JMenuItem transTable10 = new JMenuItem("transl_table = 10");
		transTable.add(transTable10);
		JMenuItem transTable11 = new JMenuItem("transl_table = 11");
		transTable.add(transTable11);
		JMenuItem transTable12 = new JMenuItem("transl_table = 12");
		transTable.add(transTable12);
		JMenuItem transTable13 = new JMenuItem("transl_table = 13");
		transTable.add(transTable13);
		JMenuItem transTable14 = new JMenuItem("transl_table = 14");
		transTable.add(transTable14);
		JMenuItem transTable15 = new JMenuItem("transl_table = 15");
		transTable.add(transTable15);
		JMenuItem transTable16 = new JMenuItem("transl_table = 16");
		transTable.add(transTable16);
		JMenuItem transTable21 = new JMenuItem("transl_table = 21");
		transTable.add(transTable21);
		JMenuItem transTable22 = new JMenuItem("transl_table = 22");
		transTable.add(transTable22);
		JMenuItem transTable24 = new JMenuItem("transl_table = 24");
		transTable.add(transTable24);

		transTable1.setActionCommand("1");
		transTable1.addActionListener(transTableListener);
		transTable2.setActionCommand("2");
		transTable2.addActionListener(transTableListener);
		transTable3.setActionCommand("3");
		transTable3.addActionListener(transTableListener);
		transTable4.setActionCommand("4");
		transTable4.addActionListener(transTableListener);
		transTable5.setActionCommand("5");
		transTable5.addActionListener(transTableListener);
		transTable6.setActionCommand("6");
		transTable6.addActionListener(transTableListener);
		transTable9.setActionCommand("9");
		transTable9.addActionListener(transTableListener);
		transTable10.setActionCommand("10");
		transTable10.addActionListener(transTableListener);
		transTable11.setActionCommand("11");
		transTable11.addActionListener(transTableListener);
		transTable12.setActionCommand("12");
		transTable12.addActionListener(transTableListener);
		transTable13.setActionCommand("13");
		transTable13.addActionListener(transTableListener);
		transTable14.setActionCommand("14");
		transTable14.addActionListener(transTableListener);
		transTable15.setActionCommand("15");
		transTable15.addActionListener(transTableListener);
		transTable16.setActionCommand("16");
		transTable16.addActionListener(transTableListener);
		transTable21.setActionCommand("21");
		transTable21.addActionListener(transTableListener);
		transTable22.setActionCommand("22");
		transTable22.addActionListener(transTableListener);
		transTable24.setActionCommand("24");
		transTable24.addActionListener(transTableListener);

		annoMenu.add(transTable);

		JMenuItem newGenome = new JMenuItem("New Annotation");
		newGenome.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				Object[] options = { "Yes!", "No!" };
				int n = JOptionPane.showOptionDialog(viewer, "Would you like to create a new list of annotations?", "Create new list of annotations", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

				if (n == 0) {
					viewer.newAnnotatedGenome();
					viewer.getNewGenome().getListOfLoci().get(0).setLocusName(viewer.getSelectedLocus());
					viewer.getNewGenome().getListOfLoci().get(0).setLocusSize(viewer.getSizeOfReference());
					viewer.getNewGenome().getListOfLoci().get(0).setNameOfOrganism(viewer.getLoadedTracks()[1].getName());
				}
			}
		});
		annoMenu.add(newGenome);

		JMenuItem newAnnotation = new JMenuItem("Create New Bucket");
		selectedSequence.setAccelerator(KeyStroke.getKeyStroke('+'));	
		newAnnotation.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				int count = viewer.getNovelFeatureCounter();
				viewer.createNewBucketWithEmptyFeature();
				viewer.getCurrentCreatedFeature().setName("nTAR#" + count);
				viewer.getCurrentCreatedFeature().setStrand("+");
				viewer.getCurrentCreatedFeature().getAdditionalInformation().add("/gene=\"nTAR#" + count + "\"");
				viewer.getCurrentCreatedFeature().getAdditionalInformation().add("/transcript_id=\"nTAR#" + count + ".1\"");
				viewer.getCurrentCreatedFeature().setType("mRNA");
				viewer.setFeatureUnpositioned(-2);
			}
		});
		annoMenu.add(newAnnotation);
		
		JMenuItem removeAnnotation = new JMenuItem("Remove Last Bucket");
		removeAnnotation.setAccelerator(KeyStroke.getKeyStroke('-'));	
		removeAnnotation.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				viewer.removeLastBucket();
				viewer.getDrawPanel().repaint();
			}
		});
		annoMenu.add(removeAnnotation);

		JMenu settings = new JMenu("Settings");
		final ImageIcon setting = new ImageIcon(Menue.class.getResource("../resources/settings32.png"));
		settings.setIcon(setting);
		gc.gridx = 5;
		this.add(settings, gc);

		JMenuItem openGeneralColorSettings = new JMenuItem("Open General Color Settings...");
		settings.add(openGeneralColorSettings);
		openGeneralColorSettings.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				viewer.openSettings(new Tupel(4, -1), 2);
			}
		});

		JMenuItem openGeneralSizeSettings = new JMenuItem("Open General Size Settings...");
		settings.add(openGeneralSizeSettings);
		openGeneralSizeSettings.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				viewer.openSettings(new Tupel(5, -1), 2);
			}
		});

		JMenuItem saveSession = new JMenuItem("Save Current Session...");
		settings.add(saveSession);
		saveSession.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				viewer.writeLastLoadedFiles(false);
			}
		});

		settings.addSeparator();
		JMenuItem loadSettings = new JMenuItem("Load Track Settings...");
		settings.add(loadSettings);
		loadSettings.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (viewer.getFileChooser().showOpenDialog(viewer) == JFileChooser.APPROVE_OPTION) {
					try {
						viewer.setSettings(viewer.getSettings().loadSettings(viewer.getFileChooser().getSelectedFile()));
					}
					catch (Exception e1) {
						e1.printStackTrace();
					}
				}
			}
		});

		JMenu saveTrack = new JMenu("Save Track Settings");

		JMenuItem saveSettingExtra = new JMenuItem("In Extra File...");
		saveTrack.add(saveSettingExtra);
		saveSettingExtra.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (viewer.getFileChooser().showSaveDialog(viewer) == JFileChooser.APPROVE_OPTION) {
					viewer.getSettings().saveSettings(viewer.getFileChooser().getSelectedFile().getAbsolutePath());
				}
			}
		});

		JMenuItem saveSettingDefault = new JMenuItem("Set As Default");
		saveTrack.add(saveSettingDefault);
		saveSettingDefault.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				viewer.getSettings().saveSettings("settings.xml");
			}
		});
		settings.add(saveTrack);
		settings.addSeparator();

		JMenuItem fullscreen = new JMenuItem("Switch To Fullscreen");
		settings.add(fullscreen);
		settings.setMnemonic(KeyEvent.VK_F11);
		fullscreen.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (!viewer.getSettings().isFullScreen()) {
					viewer.openFullScreenMode();
				}
			}
		});

		final JMenuItem informationWindow = new JMenuItem("Show Information Window");
		informationWindow.setAccelerator(KeyStroke.getKeyStroke('i'));	

		informationWindow.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

				if (viewer.getDrawPanel().isShowInformationWindow()) {
					viewer.getDrawPanel().setShowInformationWindow(false);
					informationWindow.setIcon(null);
				}
				else {
					viewer.getDrawPanel().setShowInformationWindow(true);
					informationWindow.setIcon(selectecIcon);
				}
			}
		});
		settings.add(informationWindow);
		
		final JMenuItem fixInfoWindow = new JMenuItem("Fix Information Window");
		settings.add(fixInfoWindow);

		fixInfoWindow.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if (viewer.getSettings().isInfoWindowLocationFixed()) {
					viewer.getSettings().setInfoWindowLocationFixed(false);
					fixInfoWindow.setIcon(null);
				}
				else {
					
					viewer.getSettings().setInfoWindowLocationFixed(true);
					fixInfoWindow.setIcon(selectecIcon);
				}
			}
		});
		
		final JMenuItem showSearchANdShift = new JMenuItem("Search&Shift");
		showSearchANdShift.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.Event.CTRL_MASK));

		settings.add(showSearchANdShift);

		showSearchANdShift.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if (viewer.isSearchShiftVisible()) {
					viewer.setSearchShiftVisible(false);
					showSearchANdShift.setIcon(null);
				}
				else {
					
					viewer.setSearchShiftVisible(true);
					showSearchANdShift.setIcon(selectecIcon);
				}
			}
		});
	}
}
